package com.cyss.greenball.world;

import java.util.Set;

import org.jbox2d.collision.CircleDef;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;

import com.cyss.greenball.exception.GameOverException;
import com.cyss.greenball.util.SystemUtil;

import android.graphics.Canvas;

public class GreenBall extends ElementObject {
	private float x, y, r;
	private Body body;
	private boolean isConnectFlag = false;
	private int connectHoleType;
	private float checkAccuracy = 1.5f;

	public GreenBall(BallWorld world, float x, float y, float r) {
		super(world);
		this.x = x;
		this.y = y;
		this.r = r;
		instance();
	}

	@Override
	public void instance() {
		CircleDef shape = new CircleDef();
		shape.density = 7.0f;
		shape.friction = 0.2f;
		shape.radius = r / SystemUtil.RATE;

		BodyDef bodyDef = new BodyDef();
		bodyDef.position.set(x / SystemUtil.RATE, y / SystemUtil.RATE);
		body = super.world.createBody(bodyDef);
		body.createShape(shape);
		body.setMassFromShapes();
	}

	@Override
	public void onDraw(Canvas canvas) throws GameOverException {
		float x = body.getPosition().x * SystemUtil.RATE;
		float y = body.getPosition().y * SystemUtil.RATE;
		Set<Hole> holeSet = super.ballWorld.getHoleElement();
		for (Hole hole : holeSet) {
			if (x < hole.x + hole.r / checkAccuracy
					&& x > hole.x - hole.r / checkAccuracy
					&& y < hole.y + hole.r / checkAccuracy
					&& y > hole.y - hole.r / checkAccuracy) {
				System.out.println("game over");
				x = hole.x;
				y = hole.y;
				isConnectFlag = true;
				connectHoleType = hole.getHoleType();
				break;
			}
		}
		canvas.drawCircle(x, y, r, paint);
		if (isConnectFlag) {
			GameOverException goe = new GameOverException();
			if (connectHoleType == Hole.TRAP) {
				goe.setGameOverFlag(SystemUtil.GAME_STATE_FAIL);
			} else if (connectHoleType == Hole.DESTINY) {
				goe.setGameOverFlag(SystemUtil.GAME_STATE_SUCCESS);
			}
			throw goe;
		}
	}
}
